package com.community.controller;

import com.alibaba.fastjson.JSON;
import com.community.dto.GiteeUser;
import com.community.dto.TokenDTO;
import com.community.mapper.UserMapper;
import com.community.pojo.User;
import com.community.provider.GiteeProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * @author 赵德胤
 * @create 2020-05-31-23:47
 *
 * 使用码云登录的时候需要调用回调地址，在这里配置用户token信息
 **/
@Controller
public class AuthorController {

    @Autowired
    private GiteeProvider giteeProvider;

    @Value("${gitee.grant.type}")
    private String grant_type;
    @Value("${gitee.client.id}")
    private String client_id;
    @Value("${gitee.client.secret}")
    private String client_secret;
    @Value("${gitee.redirect.uri}")
    private String redirect_uir;

    @Autowired
    UserMapper userMapper;

    @GetMapping("/callback")
    public String callback(@RequestParam("code")String code, HttpSession session){
        TokenDTO tokenDTO = new TokenDTO();
        tokenDTO.setCode(code);
        tokenDTO.setGrant_type(grant_type);
        tokenDTO.setClient_id(client_id);
        tokenDTO.setClient_secret(client_secret);
        tokenDTO.setRedirect_uri(redirect_uir);
        String token = giteeProvider.getToken(tokenDTO);
        GiteeUser giteeUser = giteeProvider.getUser(token);
        if(giteeUser != null){//登录成功
            User user = new User();
            user.setAccountId(String.valueOf(giteeUser.getId()));
            user.setName(giteeUser.getName());
            user.setToken(UUID.randomUUID().toString());
            user.setCreateTime(System.currentTimeMillis());
            user.setModifiedTime(user.getCreateTime());
            userMapper.insert(user);
            session.setAttribute("user",user);
            return "redirect:index";
        }else{//登录失败
            return "redirect:index";
        }
    }
}
